BigDFT.YamlDict module

YamlDict is a simple DictType MutableMapping object that mirrors its state to a YAML compliant file

YamlDict behaves in most ways like a standard dictionary, with the added effect that all changes are mirrored to a YAML file at fname.

Initialise either with a dict, or initialise empty and assign just as with a standard dict:

>>> a = YamlDict({'key': 'value'})
>>> b = YamlDict()
>>> b['key'] = 'value'
>>> print(a == b)
>>> True

Because all changes are synced to file, YamlDicts initialised to the same filename will share values:

>>> a = YamlDict({'key': 'value'}, fname = 'test.yaml')
>>> b = YamlDict(fname = 'test.yaml')
>>> print(b.dict)
>>> {'key': 'value'}

Additionally, a YamlDict initialised on top of a file with data in it will add any initial data to that file

>>> a = YamlDict({'firstval': 1}, fname='merge.yaml')
>>> b = YamlDict({'secondval': 2}, fname='merge.yaml')
>>> print(b.dict)
>>> {'firstval': 1, 'secondval': 2}

Unless you pass overwrite=True, in which case the new YamlDict will be enforced to the state at initialisation:

>>> c = YamlDict(fname='merge.yaml', overwrite=True)
>>> print(c.dict)
>>> {}
>>> d = YamlDict({'newval': 'val'}, fname='merge.yaml', overwrite=True)
>>> print(d.dict)
>>> {'newval': 'val'}

YamlDict also has inbuilt name validation. Any fname passed will be converted to an os.path.abspath string, and the filetype enforced to .yaml (or .yml)

Note

Nested objects can currently pose problems if they are being dynamically updated, as shown here:

>>> test = YamlDict({'a': {'b': 2}})
>>> test['a']['b'] = 10
>>> print(test.dict)
>>> {'a': {'b': 2}}
class YamlDict(initial: Optional[dict] = None, fname: str = 'database.yaml', overwrite: bool = False)[source]

DictType Object for storing data in a YAML formatted database

Parameters
  • initial (dict, optional) – initial dict to start with

  • fname (str, optional) – filename for the database

  • overwrite (bool, optional) – overwrite file with initial, or empty dict

read()[source]

Read the yaml file into the internal dict.

Shouldn’t be necessary for the user to call this method, but can be done so in order to force an update or for debugging

Returns

loaded dict as stored internally

Return type

dict

write()[source]

Export the internal dict to yaml file.

Shouldn’t be necessary for the user to call this method, but can be done so in order to force an update or for debugging

Returns

internal dict as written

Return type

dict

property dict

Return the internal dict

Returns

internal dict

Return type

dict